import { useState } from 'react'
import './index.less'
import { Button, Input, Form } from 'antd';
import * as dayjs from 'dayjs'
import axios from "axios";
import { Configuration, OpenAIApi } from 'openai'
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { useEffect } from 'react';

export default function Test() {
  const replyWithText = async() => {
    const configuration = new Configuration({
      apiKey: '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'
    });
    const openai = new OpenAIApi(configuration);
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: input,
      temperature: 0.9,
      max_tokens: 20,
      top_p: 1,
      frequency_penalty: 0.0,
      presence_penalty: 0.6,
      stop: [" Human:", " AI:"],
    });
    const currentChat = response.data.choices.map(obj => {
      return {
        ...obj,
        created: response.data.created,
        id: response.data.id
      }
    })
    setChats(chats.concat(currentChat))
    setInput('')
  }

  const replyWithImg = async() => {
    const configuration = new Configuration({
      apiKey: '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',
    });
    const openai = new OpenAIApi(configuration);
    const response = await openai.createImage({
      prompt: input,
      n: 2,
      size: "512x512",
    });
    const currentChat = response.data.data.map(obj => {
      return {
        ...obj,
        created: response.data.created,
        id: response.data.id
      }
    })
    setChats(chats.concat(currentChat))
    setInput('')
  }

  const replyWIthStream = async() => {
    let currentText = ''
    let currentId = 0
    const controller = new AbortController();
    fetchEventSource ('https://api.openai.com/v1/completions', {
      method: 'POST',
      headers: {
        "Authorization": "Bearer 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",
        "Content-Type": 'application/json',
      },
      body: JSON.stringify({
        "model": "text-davinci-003",
        // "prompt": '给我推荐一些威士忌',
        "prompt": input,
        "max_tokens": 200,
        "stream": true,
      }),
      signal: controller.signal,
      onmessage(event) {
        const res = JSON.parse(event.data)
        // console.log(res)
        if ((currentId === 0) || (currentId === res.id)) {
          currentId = res.id
          currentText += res.choices[0].text
          setChats((prev) => {
            const prevObj = prev.find(obj => obj.id === currentId)
            if (prevObj) {
              return prev.map(obj => {
                if (obj.id === currentId) {
                  return { ...obj, text: currentText }
                } else {
                  return obj
                }
              })
            } else {
              return prev.concat([{
                id: currentId,
                text: currentText,
                created: res.created,
              }])
            }
          })
        } else {
          controller.abort()
          setInput('')
        }
      },
      onerror() {
        
      }
    })
  }

  const [input, setInput] = useState('')
  const [chats, setChats] = useState([])
  const changeInput = (e) => {
    setInput(e.target.value)
  }

  return (
    <div className="chat">
      <Input.Group compact>
        <Input style={{ width: 'calc(100% - 200px)' }} value={input} onChange={changeInput} />
        <Button type="primary" onClick={replyWithText}>生成对话</Button> 
        <Button type="danger" onClick={replyWithImg}>生成图片</Button>
        <Button type="warn" onClick={replyWIthStream}>逐步生成对话</Button>
      </Input.Group>
      <ul>
        {
          chats.map(obj => {
            return obj.text ? <li key={obj.id}>{dayjs(obj.created * 1000).format('YYYY-MM-DD HH:mm:ss')} : {obj.text}</li> : <li key={obj.url}><img src={obj.url} alt="" /></li>
          })
        }
      </ul>
    </div>
  )
}